using System.Collections.Generic;
using UnityEngine;

namespace ai_library
{
	public class Agent : Entity, IEntityStateMachine<Agent>
	{
		private const float feelerLength = 8.0f;

		private IStateMachine<Agent> m_stateMachine;

		public Agent(Transform transform, Vector2 velocity, 
		             float mass, float maxSpeed, float maxForce, float maxTurnRate, float bRadius)
			: base(transform, velocity, mass, maxSpeed, maxForce, maxTurnRate, bRadius)
		{
			Feelers.Add(Forward * feelerLength);
			Feelers.Add(Left * feelerLength);
			Feelers.Add(Right * feelerLength);

			try
			{
				m_stateMachine = new StateMachine<Agent>(this);
				m_stateMachine.ChangeCurrentState(IdleState<Agent>.Instance);
				m_stateMachine.ChangeGlobalState(GlobalMessagingState<Agent>.Instance);
			}
			catch(StateMachineException e)
			{
				throw new EntityException(e.ToString());
			}
		}

		public IState<Agent> CurrentState
		{
			get; set;
		}
		
		public IState<Agent> GlobalState
		{
			get; set;
		}

		public IStateMachine<Agent> StateMachine
		{
			get
			{
				return m_stateMachine;
			}
		}

		public override void Update (float dt)
		{
			base.Update(dt);

			float feelerSpeedMult = (Velocity.magnitude / MaxSpeed) * 5.0f;

			float feelerMagnitude = feelerSpeedMult + feelerLength;

			Feelers.Clear();
			Feelers.Add(Forward * feelerMagnitude);
			Feelers.Add(Left * feelerMagnitude);
			Feelers.Add(Right * feelerMagnitude);

			try
			{
				m_stateMachine.Update(dt);
			}
			catch(StateMachineException e)
			{
				throw new EntityException(e.ToString());
			}
		}

		public override bool ProcessMessage(Message m)
		{
			if (!StateMachine.ProcessMessage(m))
			{
				Debug.Log ("Message Not processed: " + m.ToString());

				return false;
			}

			return true;
		}
	}
}
